package com.hzk.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Configuration
public class DeadLetterMQConfig {

    /**
     * 订单交换机
     */
    private String orderExchange="mayikt_order_exchange";

    /**
     * 订单队列
     */
    private String orderQueue="mayikt_order_queue";

    /**
     * 订单路由key
     */
    private String orderRoutingKey="mayikt.order";

    /**
     * 死信交换机
     */
    private String dlxExchange="mayikt_order_dlx_exchange";

    /**
     * 死信队列
     */
    private String dlxQueue="mayikt_order_dlx_queue";
    /**
     * 死信路由
     */
    private String dlxRoutingKey="mayikt.order";

    //死信交换机
    @Bean
    public DirectExchange dlxExchange() {
        return new DirectExchange(dlxExchange);
    }


    //声明死信队列 (真正的队列)

    @Bean
    public Queue dlxQueue() {
        return new Queue(dlxQueue);
    }

    /**
     * 声明订单业务交换机(基本交换机)
     */
    @Bean
    public DirectExchange orderExchange() {
        return new DirectExchange(orderExchange);
    }

    /**
     * 声明订单队列（用于基本交换机和基本路由到死信队列的绑定）
     */
    @Bean
    public Queue orderQueue() {
        Map<String, Object> arguments = new HashMap<>(2);
        // 绑定我们的死信交换机
        arguments.put("x-dead-letter-exchange", dlxExchange);
        // 绑定我们的路由key
        arguments.put("x-dead-letter-routing-key", dlxRoutingKey);
        return new Queue(orderQueue, true, false, false, arguments);
    }

    /**
     * (创建基本交换机+基本路由 -> 死信队列 的绑定)
     */
    @Bean
    public Binding orderBinding() {
        return BindingBuilder.bind(orderQueue()).to(orderExchange()).with(orderRoutingKey);
    }

    /**
     * （死信交换机+死信路由->真正队列 的绑定）
     */
    @Bean
    public Binding binding() {
        return BindingBuilder.bind(dlxQueue()).to(dlxExchange()).with(dlxRoutingKey);
    }
}
